<?php

namespace oa\services;

use Yii;
use oa\models\DeliveryCompany;

class DeliveryCompanyService extends BaseService
{
    public static function save($post)
    {
        if (empty($post['id'])) {
            $model = new DeliveryCompany();
        } else {
            $model = static::one($post['id']);
        }
        return $model->_save($post);
    }

    public static function getList()
    {
        $req = Yii::$app->request;
        $query = DeliveryCompany::find();
        $query->where('status<>-1');
        $query->filterWhere(['status' => $req->get('status')]);
        $query->andFilterWhere(['like', 'name', Yii::$app->request->get('name')]);
        $query->orderBy(['created_at' => SORT_DESC]);
        $rows = $query->offset($req->get('offset'))->limit($req->get('limit'))->asArray()->all();
        foreach ($rows as $k => $v) {
            $rows[$k]['created_at'] = date('Y-m-d H:i', $v['created_at']);
        }
        return ['rows' => $rows];
    }

    public static function getAll()
    {
        return DeliveryCompany::find()->select('name')->where('status=1')->orderBy(['created_at' => SORT_DESC])->asArray()->indexBy('id')->column();
    }

    public static function one($map, $toArray = 0)
    {
        $query = DeliveryCompany::find()->where('status>0');
        if (is_numeric($map) && preg_match('/^[1-9]+[\d]*$/', $map)) {
            $query->andWhere('id=:id', [':id' => $map]);
        } elseif (is_array($map)) {
            $query->andWhere($map[0], $map[1]);
        } else {
            $query->andWhere($map);
        }
        if ($toArray == 1) {
            $query->asArray();
        }
        return $query->one();
    }

    public static function remove($id)
    {
        $model = static::one(['id=:id AND status<>-1', [':id' => $id]]);
        $model->scenario = DeliveryCompany::SCENARIO_REMOVE;
        $model->status = -1;
        return $model->_save();
    }

    public static function disable($id)
    {
        $model = static::one(['id=:id AND status=1', [':id' => $id]]);
        $model->scenario = DeliveryCompany::SCENARIO_DISABLE;
        $model->status = 2;
        return $model->_save();
    }

    public static function enable($id)
    {
        $model = static::one(['id=:id AND status=2', [':id' => $id]]);
        $model->scenario = DeliveryCompany::SCENARIO_ENABLE;
        $model->status = 1;
        return $model->_save();
    }
}